import { apiGetOrderList, apiOrderClose, apiOrderTakeDelivery, apiDelOrderShareById } from '../../api/index'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    orderList: [ '全部', '待付款', '待发货', '待收货', ' 待接力', '已完成' ],
    selectIndex: 0,
    allOrder: [],
    noOrder: false,
    loadMore: false,
    loads: true,
    relay: 2, // 1接力 2正常
    showTime: []
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad (options) {
    this.params = {}
    this.params['status'] = options.index ? (options.index - 0) + 1 : 0
    this.params['page'] = 1
    let selectIndex = 0
    if (options.index) {
      selectIndex = (options.index - 0) + 1
    }
    this.setData({
      selectIndex,
      isIphoneX: getApp().globalData.isIphoneX,
      navHeight: getApp().globalData.navHeight
    })
    this.init()
  },
  init () {
    this.getAllOrder()
  },
  // 点击
  changeState (i) {
    this.params['status'] = i.currentTarget.dataset.index
    this.params['page'] = 1
    this.setData({
      selectIndex: i.currentTarget.dataset.index
    })
    this.init()
  },
  // 获取全部订单
  getAllOrder () {
    apiGetOrderList(this.params).then(
      res => {
        let allOrder = this.data.allOrder
        if (this.params.page === 1) {
          allOrder = []
        }
        let data = res.data.data
        for (let i = 0; i < data.length; i++) {
          if ((data[i].relay_status - 0) === 0) {
            data[i].timeOver = true
          } else {
            data[i].timeOver = false
          }
          if (data[i].order_share_create_time) {
            const createTime = data[i].order_share_create_time + data[i].valid_time * 60
            data[i].end_time = createTime - new Date().getTime() / 1000
            if (this.params.status === 4) {
              this.timestampToTime(data[i].end_time, i)
            }
          }
        }
        let more = false
        let noOrder = false
        if (data.length >= 20) {
          more = true
        }
        if (data.length <= 0 && allOrder.length <= 0) {
          noOrder = true
        } else {
          noOrder = false
        }
        allOrder = allOrder.concat(data)
        wx.hideLoading()
        this.setData({
          allOrder,
          loadMore: more,
          noOrder,
          loads: false
        })
        wx.stopPullDownRefresh()
      }
    )
  },
  timestampToTime (s, index) {
    let showTime = this.data.showTime
    if (s > 0) {
      this.times = setTimeout(() => {
        let h = Math.floor(s / 3600 % 24)
        let min = Math.floor(s / 60 % 60)
        let sec = Math.floor(s % 60)
        h = this.add(h)
        min = this.add(min)
        sec = this.add(sec)
        showTime[index] = `${h}:${min}:${sec}`
        this.setData({
          showTime
        })
        s -= 1
        if (s <= 0) {
          this.clearAllTimer()
          this.init()
        } else {
          this.timestampToTime(s, index)
        }
      }, 1000)
    }
  },
  add (m) {
    return m < 10 ? '0' + m : m
  },
  // 取消订单
  closeOrder (e) {
    wx.showModal({
      title: '提示',
      content: '您确定取消该订单吗？',
      success: (res) => {
        if (res.confirm) {
          apiOrderClose({ order_id: e.target.dataset.id }).then(
            res => {
              wx.showToast({
                title: '已关闭',
                success: () => {
                  this.init()
                }
              })
            }
          )
        } else if (res.cancel) {
        }
      }
    })
  },
  //  分享
  shareFriend (e) {
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `../share/share?order_id=${id}`
    })
  },
  // 删除订单
  // cancleOrder (e) {
  //   apiDeleteOrder({ order_id: e.target.dataset.id }).then(
  //     res => {
  //
  //       wx.showModal({
  //         title: '提示',
  //         content: '您确定删除该订单吗？',
  //         success: (res) => {
  //           if (res.confirm) {
  //             wx.showToast({
  //               title: '删除成功',
  //               success: () => {
  //                 this.setData({
  //                   allOrder: []
  //                 })
  //                 this.getAllOrder()
  //               }
  //             })
  //           } else if (res.cancel) {
  //           }
  //         }
  //       })
  //     }
  //   )
  // },
  // 去支付
  goPay (e) {
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `../payment/payment?id=${id}`
    })
  },
  // 确认收货
  isSureReceipt (e) {
    wx.showModal({
      title: '提示',
      content: '是否确认收货？',
      success: (res) => {
        if (res.confirm) {
          apiOrderTakeDelivery({ order_id: e.target.dataset.id }).then(
            res => {
              wx.showToast({
                title: '已收货',
                success: () => {
                  this.init()
                }
              })
            }
          )
        } else if (res.cancel) {
        }
      }
    })
  },
  goToDetail (e) {
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `../order-detail/order-detail?id=${id}`
    })
  },
  // 查看物流
  lookLogistics (e) {
    let id = e.target.dataset.id
    wx.navigateTo({
      url: `../logistics/logistics?id=${id}`
    })
  },
  toRelay (e) {
    wx.navigateTo({
      url: `../relay/index?id=${e.currentTarget.dataset.id}`
    })
  },
  // 删除接力记录
  cancelRelay (e) {
    console.log(e.currentTarget.dataset.id)
    wx.showModal({
      title: '删除接力记录',
      content: '您确定删除该订单吗？',
      success: (success) => {
        if (success.confirm) {
          apiDelOrderShareById({ order_id: e.currentTarget.dataset.id }).then(
            res => {
              console.log(res)
              wx.showToast({
                title: '接力订单已删除',
                icon: 'none',
                success: () => {
                  this.setData({
                    allOrder: []
                  })
                  this.getAllOrder()
                }
              })
            }
          )
        } else if (success.cancel) {
        }
      }
    })
  },
  clearAllTimer () {
    clearTimeout(this.times)
    this.times = null
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady () {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide () {
    this.clearAllTimer()
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload () {
    this.clearAllTimer()
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh () {
    wx.showLoading({
      title: '加载中'
    })
    this.params['page'] = 1
    this.init()
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom () {
    if (this.data.loadMore) {
      this.params['page']++
      this.getAllOrder()
    }
  }
})
